package com.demo.chapter13functionprogramming;

import java.util.stream.IntStream;

//阶乘
public class Demo {

	//传统方式
	public static int demo1(int n){
		int r = 1;
		for(int i=1; i<=n; i++){
			r *= i;
		}
		return r;
	}

	//递归
	public static int demo2(int n){
		return n == 1 ? 1 : n * demo2(n - 1);
	}

	//基于stream
	public static int demo3(int n){
		return IntStream.rangeClosed(1, n).reduce((a, b) -> a * b).orElse(0);
	}

	//尾递归：迭代发生在函数的最后
	public static int demo4(int n){
		return factorial(1, n);
	}

	//acc每次递归的结果，n递归次数
	private static int factorial(int acc, int n){
		return n == 1 ? acc : factorial(acc * n, n - 1);
	}

	public static void main(String[] args) {
		System.out.println(demo1(5));
		System.out.println(demo2(5));
		System.out.println(demo3(5));
		System.out.println(demo4(5));
	}

}
